package cn._51doit.flink.day03;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class MinByDemo2 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //辽宁省,沈阳市,2000
        //山东省,济南市,3000
        //辽宁省,大连市,1000
        //辽宁省,鞍山市,1000
        //山东省,烟台市,1000
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple3<String, String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple3<String, String, Integer>>() {
            @Override
            public Tuple3<String, String, Integer> map(String s) throws Exception {
                String[] fields = s.split(",");
                String province = fields[0];
                String city = fields[1];
                int money = Integer.parseInt(fields[2]);
                return Tuple3.of(province, city, money);
            }
        });


        KeyedStream<Tuple3<String, String, Integer>, String> keyed = tpStream.keyBy(t -> t.f0);

        //如果要处理的数据，除了keyBy和比较大写的字段外，还有其他字段，那么其他字段就不准确了，返回的是第一次出现的字段值
        //SingleOutputStreamOperator<Tuple3<String, String, Integer>> res = keyed.min(2);

        //SingleOutputStreamOperator<Tuple3<String, String, Integer>> res = keyed.minBy(2);
        SingleOutputStreamOperator<Tuple3<String, String, Integer>> res = keyed.minBy(2, false);

        res.print();

        env.execute();

    }
}
